package tcp;

import java.io.*;
import java.net.*;
import java.util.HashMap;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/17
 * Time:15:34
 **/
public class Server {
    /**
     * 服务器端-"智能" 翻译机器人
     */
    //端口号
    private static final int port = 1001;
    //翻译
    static HashMap<String, String> map = new HashMap<>();

    static {
        map.put("dog", "狗🐕");
        map.put("cat", "猫🐱");
        map.put("pig", "猪🐖");
    }

    public static void main(String[] args) throws IOException {
        //1.启动服务器端
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器已启动！");

        //2.等待连接客户端
        Socket socket = serverSocket.accept();
        //打印连接信息
        System.out.println(String.format("已连接到客户端,ip:%s,port:%d",
                socket.getInetAddress().getHostAddress(),
                socket.getPort()
        ));//说明有客户端连接

        //3.创建读写对象
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())
        );
             BufferedReader reader = new BufferedReader(
                     new InputStreamReader(socket.getInputStream())
             )
        ) {
            while (true) {
                //4.获取英文
                String english = reader.readLine();
                if (english != null && !english.equals("")) {
                    //5.翻译
                    String china = transEnglish(english);
                    //6.将结果给客户端
                    writer.write(china + "\n");//不能省略\n
                    writer.flush();// 将发送缓冲区的消息立即发送
                }
            }
        }
    }

    private static String transEnglish(String english) {
        String china = null;
        china = map.get(english);
        return china == null ? "未知" : china;
    }
}
